package com.example.demo.controller;


import com.example.demo.entity.Student;
import com.example.demo.object.StudentQo;
import com.example.demo.service.StudentService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/student")
public class StudentController {
    private static Logger logger = LoggerFactory.getLogger(StudentController.class);

    @Autowired
    private StudentService studentService;

    @RequestMapping("/index")
    public String index(ModelMap model, HttpServletRequest request) throws Exception{
        return "student/index";
    }

    @RequestMapping(value="/{id}")
    public String show(ModelMap model, @PathVariable Long id) {
        Student student = studentService.findById(id);
        model.addAttribute("student", student);
        return "student/show";
    }

    @RequestMapping(value="/list")
    @ResponseBody
    public Page<Student> findAll(StudentQo studentQo) {
        return studentService.findAll(studentQo);
    }

    @RequestMapping("/new")
    public String create(){
        return "student/new";
    }

    @RequestMapping(value="/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(Student student) throws Exception{
        if(studentService.save(student)) {
            logger.info("保存成功！");
            return "1";
        }else{
            return "-1";
        }
    }

    @RequestMapping(value="/edit/{id}")
    public String edit(ModelMap model, @PathVariable Long id){
        Student student = studentService.findById(id);

        model.addAttribute("student", student);

        return "student/edit";
    }

    @RequestMapping(method = RequestMethod.POST, value="/update")
    @ResponseBody
    public String update(Student student) throws Exception{
        if(studentService.save(student)) {
            logger.info("编辑成功！");
            return "1";
        }else {
            return "-1";
        }
    }

    @RequestMapping(value="/delete/{id}",method = RequestMethod.GET)
    @ResponseBody
    public String delete(@PathVariable Long id) throws Exception{
        if(studentService.deleteById(id)) {
            logger.info("删除成功！");
            return "1";
        }else{
            return "-1";
        }
    }

}
